<template>
  <div class="storyBoard">
    <el-affix :offset="152">
      <div class="rowHeader">
        <div class="title" :style="{width: cardWidth + 'px'}"><div>未开始</div><div class="icon unstart">{{unstartCount}}</div></div>
        <div class="title" :style="{width: cardWidth + 'px'}"><div>开发中</div><div class="icon indevelop">{{startCount}}</div></div>
        <div class="title" :style="{width: cardWidth + 'px'}"><div>阻塞</div><div class="icon inWay">{{inFileCount}}</div></div>
        <div class="title" :style="{width: cardWidth + 'px'}"><div>已完成</div><div class="icon finish">{{finishedCount}}</div></div>
      </div>
    </el-affix>
    <div class="row" v-for="(item, index) in storyList" :key="index">
      <div class="col-3">
        <div class="title">
          <el-icon v-show="!item.openType" @click="itemClickHandler(item)"><caret-right /></el-icon>
          <el-icon v-show="item.openType" @click="itemClickHandler(item)"><caret-bottom /></el-icon>
          <span class="requireType">{{item.requireType}}</span>
          <span @click="searchItem(item)">{{item.title}}</span>
          <span class="developType" :style="{color: item.developType === '未开始' ? '#520EF9 ' : item.developType === '开发中' ? '#4091FD' : item.developType === '阻塞' ? '#FF5257' : '#7ED321'}">{{item.developType}}</span>
        </div>
        <draggable
          :animation="300"
          dragClass="dragClass"
          class="list-group"
          :list="item.list1"
          :group="item.group1"
          @change="log($event, item)"
          itemKey="name"
          v-show="item.openType" 
        >
          <!-- <template #item="{ element, index }"> -->
          <template #item="{ element }">
            <div class="list-group-item" @click="searchItem(element)" @mousedown="dragItemClickHandler(item, 1, element)">
              <div class="requireHead">
                <div class="requireType">{{element.itemType}}</div>
                <div class="requireName">{{element.demandName}}</div>
              </div>
              <div class="requireBody">
                <div class="developType">优先级：{{element.priority}}</div>
                <div class="developTime">{{element.developerName}}</div>
              </div>
            </div>
            
          </template>
        </draggable>
      </div>

      <div class="col-3">
        <draggable
          :animation="300"
          dragClass="dragClass"
          class="list-group"
          :list="item.list2"
          :group="item.group2"
          @change="log($event, item)"
          itemKey="name"
           v-show="item.openType" 
        >
          <!-- <template #item="{ element, index }"> -->
          <template #item="{ element }">
            <div class="list-group-item" @click="searchItem(element)" @mousedown="dragItemClickHandler(item, 2, element)">
              <div class="requireHead">
                <div class="requireType">{{element.itemType}}</div>
                <div class="requireName">{{element.demandName}}</div>
              </div>
              <div class="requireBody">
                <div class="developType">优先级：{{element.priority}}</div>
                <div class="developTime">{{element.developerName}}</div>
              </div>
            </div>
          </template>
        </draggable>
      </div>

      <div class="col-3">
        <draggable
          :animation="300"
          dragClass="dragClass"
          class="list-group"
          :list="item.list3"
          :group="item.group3"
          @change="log($event, item)"
          itemKey="name"
           v-show="item.openType" 
        >
          <!-- <template #item="{ element, index }"> -->
          <template #item="{ element }">
            <div class="list-group-item" @click="searchItem(element)" @mousedown="dragItemClickHandler(item, 3, element)">
              <div class="requireHead">
                <div class="requireType">{{element.itemType}}</div>
                <div class="requireName">{{element.demandName}}</div>
              </div>
              <div class="requireBody">
                <div class="developType">优先级：{{element.priority}}</div>
                <div class="developTime">{{element.developerName}}</div>
              </div>
            </div>
          </template>
        </draggable>
      </div>

      <div class="col-3">
        <draggable
          :animation="300"
          dragClass="dragClass"
          class="list-group"
          :list="item.list4"
          :group="item.group4"
          @change="log($event, item)"
          itemKey="name"
           v-show="item.openType" 
        >
          <!-- <template #item="{ element, index }"> -->
          <template #item="{ element }">
            <div class="list-group-item" @click="searchItem(element)" @mousedown="dragItemClickHandler(item, 4, element)">
              <div class="requireHead">
                <div class="requireType">{{element.itemType}}</div>
                <div class="requireName">{{element.demandName}}</div>
              </div>
              <div class="requireBody">
                <div class="developType">优先级：{{element.priority}}</div>
                <div class="developTime">{{element.developerName}}</div>
              </div>
            </div>
          </template>
        </draggable>
      </div>
    
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, watch } from 'vue'
import { useStore } from 'vuex'
import draggable from 'vuedraggable'
import { DArrowRight, DArrowLeft, CaretRight, CaretBottom } from '@element-plus/icons'
import { ElMessage } from 'element-plus'
import { iterationRequireListApi, requireStyleChangeApi } from '@/api/System/project'

export default defineComponent({
  components: { draggable, DArrowRight, DArrowLeft, CaretRight, CaretBottom, },
  setup () {
    const store = useStore()
    const state = reactive({
      // 任务列表
      storyList: [],
      // 当前需求ID
      currentRequireId: null,
      // 未开始的个数
      unstartCount: 0,
      // 开始的个数
      startCount: 0,
      // 阻塞的个数
      inFileCount: 0,
      // 完成的个数
      finishedCount: 0,
      // 整个宽度
      totalWidth: null,
      // 内容的宽度
      cardWidth: null
    })

    // 当前迭代ID改变请求数据
    watch(
      () => store.state.system.currentIteId,
      () => {
        getStorys()
      }
    )

    // 监听窗口大小改变
    const changeStyle = () => {
      state.cardWidth = (window.innerWidth - 30) / 4
    }

    changeStyle()

    const add = function() {
    }

    const replace = function() {
    }

    const clone = function(el) {
      return {
        name: el.name + " cloned"
      };
    }

    // 拖拽的事件
    const log = async (evt, item) => {
      let res
      if(evt.added) {
        if(item.list1[evt.added.newIndex] && item.list1[evt.added.newIndex].id === evt.added.element.id ) {
          res = await requireStyleChangeApi({
            id: state.currentRequireId,
            developStatus: '未开始',
            updator: store.state.user.name
          })
        }
        if(item.list2[evt.added.newIndex] && item.list2[evt.added.newIndex].id === evt.added.element.id ) {
          res = await requireStyleChangeApi({
            id: state.currentRequireId,
            developStatus: '开发中',
            updator: store.state.user.name
          })
        }
        if(item.list3[evt.added.newIndex] && item.list3[evt.added.newIndex].id === evt.added.element.id ) {
          res = await requireStyleChangeApi({
            id: state.currentRequireId,
            developStatus: '阻塞',
            updator: store.state.user.name
          })
        }
        if(item.list4[evt.added.newIndex] && item.list4[evt.added.newIndex].id === evt.added.element.id ) {
          res = await requireStyleChangeApi({
            id: state.currentRequireId,
            developStatus: '已完成',
            updator: store.state.user.name
          })
        }
      // @ts-ignore
        if(res.code === '0') {
          ElMessage({
            showClose: true,
            type: "success",
            message: "修改成功!",
          });
          getStorys()
        }
      }
      getStorys()
    }

    const itemClickHandler = (item) => {
      item.openType = !item.openType
    }
    
    // item点击修改设置范围和id
    const dragItemClickHandler = (item, index, element) => {
      if(index === 1) {
        const priority = element.priority ? parseInt(element.priority) : 0
        // 优先级判断
        const priorityIndex = item.list1.findIndex(task => parseInt(task.priority) > priority)
        if(priorityIndex !== -1) {
          // 有优先级更高的
          ElMessage({
            showClose: true,
            type: "error",
            message: "请先选择优先级较高的任务",
          })
          return
        }
      }
      const random = (new Date()).valueOf()
      switch(index) {
        case 1 : 
          item.group1 = random
          item.group2 = random
          break;
        case 2: 
          item.group2 = random
          item.group3 = random
          item.group4 = random
          break;
        case 3:
          item.group2 = random
          item.group3 = random
          item.group4 = random
          break;
        case 4:
          item.group4 = random
          break;
      }
      state.currentRequireId = element.id
    }

    // 查询迭代下的故事
    const getStorys = async () => {
      if(!store.state.system.currentIteId) return
      const res = await iterationRequireListApi({
        iterationId: store.state.system.currentIteId,
        productId: store.state.system.productId
      })
      // @ts-ignore
      if(res.code === '0') {
        state.storyList.length = 0
        state.unstartCount = 0
        state.startCount = 0
        state.inFileCount = 0
        state.finishedCount = 0
        if(res.data.length > 0) {
          res.data.forEach(item => {
            state.storyList.push({
              id: item.id,
              title: item.demandName,
              requireType: item.itemType,
              developType: item.developStatus,
              openType: true,
              group1: null,
              group2: null,
              group3: null,
              group4: null,
              list1: item.taskMap && item.taskMap['未开始'] || [],
              list2: item.taskMap && item.taskMap['开发中'] || [],
              list3: item.taskMap && item.taskMap['阻塞'] || [],
              list4: item.taskMap && item.taskMap['已完成'] || [],
              // 优先级转换成数值，用于排序
              priority: item.priority === '高' ? 103 : item.priority === '中' ? 102 : item.priority === '低' ? 101 : 0
            })
            state.unstartCount += item.taskMap && item.taskMap['未开始'] && item.taskMap['未开始'].length || 0
            state.startCount += item.taskMap && item.taskMap['开发中'] && item.taskMap['开发中'].length || 0
            state.inFileCount += item.taskMap && item.taskMap['阻塞'] && item.taskMap['阻塞'].length || 0
            state.finishedCount += item.taskMap && item.taskMap['已完成'] && item.taskMap['已完成'].length || 0
          })

          state.storyList.sort((a, b) => {
            return b.priority - a.priority
          })
          state.storyList.forEach(item => {
            item.list1.sort((a, b) => {
              return b.priority - a.priority
            })
            item.list2.sort((a, b) => {
              return b.priority - a.priority
            })
            item.list3.sort((a, b) => {
              return b.priority - a.priority
            })
            item.list4.sort((a, b) => {
              return b.priority - a.priority
            })
          })
        }
      }
    }

    const searchItem = (item) => {
      console.log('item', item);
      
      if(item.id) {
        store.commit('SET_REQUIREINFO', {
          content: {
            developType: null, 
            id: item.id, 
            pid: null, 
            type: 4
          },
          label: item.name
        })
      }
    }

    // 修改需求，刷新页面 
    watch(
      () => store.state.system.requireCount,
      () => {    
        getStorys()
      }
    )

    getStorys()

    return {
      ...toRefs(state),
      add,
      replace,
      clone,
      log,
      itemClickHandler,
      dragItemClickHandler,
      searchItem
    }
  }
})
</script>

<style scoped lang='scss'>
.storyBoard {
  background-color: #f5f5f5;
  width: 100%;
  height: 100%;
  .rowHeader {
    min-width: 1217px;
    width: 100%;
    height: 56px;
    display: flex;
    margin-bottom: 8px;
    .title {
      position: relative;
      flex: 1;
      margin-right: 8px;
      line-height: 56px;
      text-align: center;
      background-color: #fff;
      box-shadow: 3px 3px 12px 0px rgba(228, 228, 228, 0.5);
      border-radius: 9px;
      color: rgba(0, 0, 0, 0.85);
      font-size: 24px;
      display: flex;
      justify-content: center;
      &:nth-of-type(4) {
        margin-right: 0;
      }
      .icon {
        margin-left: 24px;
        position: relative;
        left: 0;
        top: 16px;
        width: 24px;
        height: 24px;
        background-color: red;
        font-size: 16px;
        line-height: 26px;
        border-radius: 12px;
        color: #fff;
        &.unstart {
          background-color: #520EF9;
        }
        &.indevelop {
          background-color: #4091FD;
        }
        &.inWay {
          background-color: #FF5257;
        }
        &.finish {
          background-color: #7ED321;
        }
      }
    }
  }
  .row {
    margin-bottom: 8px;
    display: flex;
    .col-3 {
      flex: 1;
      position: relative;
      min-width: 298px;
      margin-right: 8px;
      &:nth-of-type(4) {
        margin-right: 0;
      }
      width: calc(100% - 32px);
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 41px;
      box-shadow: 3px 3px 12px 0px rgba(228, 228, 228, 0.5);
      border-radius: 9px;
      background-color: #fff;
      .title {
        width: calc(100% - 32px);
        position: absolute;
        top: 11px;
        left: 16px;
        font-size: 14px;
        font-weight: 500;
        color: #333333;
        cursor: pointer;
        line-height: 24px;
        text-align: left;
        .requireType {
          text-align: center;
          display: inline-block;
          width: 48px;
          height: 24px;
          background-color: #4091FD;
          border-radius: 4px;
          color: #fff;
          margin-right: 8px;
        }
        .developType {
          position: absolute;
          top: 0;
          right: 0;
        }
      }
      .list-group {
        height: 100%;
        width: calc(100% - 32px);
        max-width: 299px;
      }
      .list-group-item {
        width: 100%;
        height: 64px;
        border-radius: 8px;
        border: 2px solid #E3E7EC;
        padding: 11px 12px;
        margin-bottom: 8px;
        cursor: pointer;
        .requireHead {
          display: flex;
          font-size: 14px;
          line-height: 20px;
          .requireType {
            color: #7ED321;
          }
          .requireName {
            margin-left: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        .requireBody {
          display: flex;
          justify-content: space-between;
          font-size: 14px;
          line-height: 20px;
        }
      }
    }
  }
}
.dragClass {
  opacity: 1 !important;
  border: 3px solid gray;
  img {
    opacity: 1 !important;
    border: 3px solid gray;
  }
}
</style>